package com.jyhs.maven.exception.handler;
import com.jyhs.maven.entity.dto.ApiResult;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.ControllerAdvice;

import java.util.HashMap;
import java.util.Map;


//@RestControllerAdvice   //注解 @RestControllerAdvice 等同于 @ControllerAdvice + @ResponseBody
@ControllerAdvice
public class T03ExceptionHandler {


    @ExceptionHandler(RuntimeException.class)
    public ModelAndView handleException(Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error");
        modelAndView.addObject("error", e.getMessage());
        e.printStackTrace();
        System.out.println("异常：" + e.getMessage());
        return modelAndView;
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public String handleMissingServletRequestParameterException(Exception e, Model model) {
        model.addAttribute("error", e.getMessage());
        System.out.println("参数异常：" + e.getMessage());
        return "error";
    }
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public String handleHttpRequestMethodNotSupportedException(Exception e, Model model) {
        model.addAttribute("error", e.getMessage());
        System.out.println("请求方式参数异常：" + e.getMessage());
        return "error";
    }

    @ExceptionHandler(Exception.class)
    public String handleException(Exception e, Model model) {
        e.printStackTrace();
        model.addAttribute("error", e.getMessage());
        System.out.println("异常：" + e.getMessage());
        return "error";
    }

    @ExceptionHandler(value = {MethodArgumentNotValidException.class, BindException.class}   )
    @ResponseBody
    public ApiResult handleMethodArgumentNotValidException(Exception e, BindingResult bindingResult) {
        e.printStackTrace();
        System.out.println("请求参数异常：" + e.getMessage());

        //遍历这些校验失败的信息
        Map<String,String> map=new HashMap<>();
        System.out.println(bindingResult.getFieldErrors());

        StringBuilder messsage=new StringBuilder();
        bindingResult.getFieldErrors().forEach(item->{

            //获取错误信息
            String defaultMessage = item.getDefaultMessage();
            //获取被校验的字段
//            String filed= item.getField();
//            map.put(filed,defaultMessage);
            messsage.append(defaultMessage).append("；");
        });

        return new ApiResult(201,messsage.toString(),null);

    }

}
